import 'package:universal_io/io.dart';

import 'package:flutter/material.dart';
//import 'package:geocoding/geocoding.dart';
import 'package:macless_haystack/accessory/accessory_icon.dart';
import 'package:macless_haystack/accessory/accessory_model.dart';
import 'package:macless_haystack/location/location_model.dart';
import 'package:intl/intl.dart';
import 'accessory_battery.dart';
import 'package:macless_haystack/location/place_info.dart';

LocationModel locationModel = LocationModel();

class AccessoryListItem extends StatefulWidget {
  final Accessory accessory;

  final Widget? distance;

  final Placeinfo? herePlace;
  final VoidCallback onTap;
  final VoidCallback? onLongPress;

  const AccessoryListItem({
    super.key,
    required this.accessory,
    required this.onTap,
    this.onLongPress,
    this.distance,
    this.herePlace,
  });

  @override
  AccessoryListItemState createState() => AccessoryListItemState();
}

class AccessoryListItemState extends State<AccessoryListItem> {
  Color _tileColor = Colors.transparent;

  @override
  Widget build(BuildContext context) {
    var hasChanged = widget.accessory.hasChangedFlag;
    if (hasChanged) {
      _tileColor = widget.accessory.color.withAlpha(50);
      Future.delayed(const Duration(seconds: 1), () {
        if (mounted) {
          widget.accessory.hasChangedFlag = false;
          setState(() {
            _tileColor = Colors.transparent;
          });
        }
      });
    }
    return FutureBuilder<Placeinfo?>(
      future: widget.accessory.place,
      builder: (BuildContext context, AsyncSnapshot<Placeinfo?> snapshot) {
        String locationString = widget.accessory.lastLocation != null
            ? '${widget.accessory.lastLocation!.latitude.toStringAsFixed(4)}, ${widget.accessory.lastLocation!.longitude.toStringAsFixed(4)}'
            : '未知';

        if (snapshot.hasData && snapshot.data != null) {
          Placeinfo place = snapshot.data!;
          if (place.name != null && place.name!.isNotEmpty) {
            locationString = '${place.name}';
          } else {
            locationString =
                '${place.province ?? ''}${place.city ?? ''}${place.district ?? ''}${place.township ?? ''}${place.street ?? ''}';
          }
        }
        // Format published date in a human readable way
        String? dateString = widget.accessory.datePublished != null &&
                widget.accessory.datePublished != DateTime(1970)
            ? ' · ${DateFormat('MM-dd HH:mm').format(widget.accessory.datePublished!)}'
            : '';

        double iconSize = 24;

        return AnimatedContainer(
          duration: const Duration(milliseconds: 300), // Sanfter Übergang
          color: _tileColor,
          child: ListTile(
            onTap: widget.onTap,
            onLongPress: widget.onLongPress,
            title: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildIcon(),
                _buildIconMargin(),
                Text(
                  widget.accessory.name +
                      (widget.accessory.isActive ? '' : ' (未激活)') +
                    dateString,
                  style: TextStyle(
                    color: widget.accessory.isActive
                        ? Theme.of(context).colorScheme.onSurface
                        : Theme.of(context).disabledColor,
                  ),
                )
              ],
            ),
            subtitle: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Text(locationString),
            ),
            trailing: widget.distance,
            dense: true,
            leading: widget.accessory.isLoadingReports
              ? Padding(
                  padding: EdgeInsets.all(iconSize / 4),
                  child: SizedBox(
                    width: iconSize,
                    height: iconSize,
                    child: CircularProgressIndicator(
                      strokeWidth: iconSize / 6,
                    ),
                  ))
              : AccessoryIcon(
              icon: widget.accessory.icon,
              color: widget.accessory.color,
            ),
          ),
        );
      },
    );
  }

  Widget _buildIcon() {
    switch (widget.accessory.lastBatteryStatus) {
      case AccessoryBatteryStatus.ok:
        return const Icon(Icons.battery_full, color: Colors.green, size: 15);
      case AccessoryBatteryStatus.medium:
        return const Icon(Icons.battery_4_bar, color: Colors.orange, size: 15);
      case AccessoryBatteryStatus.low:
        return const Icon(Icons.battery_2_bar, color: Colors.red, size: 15);
      case AccessoryBatteryStatus.criticalLow:
        return const Icon(Icons.battery_alert, color: Colors.red, size: 15);
      default:
        return const SizedBox(width: 0);
    }
  }
  
  Widget _buildIconMargin() {
    switch (widget.accessory.lastBatteryStatus) {
      case AccessoryBatteryStatus.ok:
      case AccessoryBatteryStatus.medium:
      case AccessoryBatteryStatus.low:
      case AccessoryBatteryStatus.criticalLow:
        return const SizedBox(width: 3);
      default:
        return const SizedBox(width: 0);
    }
  }
}